<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`打印付款申请`"
    :destroy-on-close="true"
    width="230mm"
    draggable
    :close-on-click-modal="false"
    @close="handleDialogClose"
  >
    <div class="printBox" id="printContent" ref="PrintRefs">
      <div style="display: flex; justify-content: space-between">
        <!--  style="letter-spacing: 2px" -->
        <div style="letter-spacing: 1px">美登思能源技术（上海）有限公司</div>
        <input
          type="text"
          class="underline-input"
          :placeholder="generateMECode() + numbercon"
          style="width: 100px; text-align: center; border: none"
        />
      </div>
      <div class="fuKtitle">付款申请</div>
      <div style="display: flex; justify-content: flex-end; margin-bottom: 10px">
        <div style="display: flex; align-items: center">
          <div style="height: 18px; line-height: 25px">申请日期：</div>
          <input
            type="text"
            class="underline-input"
            :placeholder="getCurrentDateFormatted()"
            style="width: 100px; text-align: center"
          />
        </div>
      </div>
      <div class="form-row">
        <div class="form-row-item">
          <div class="rowtitle">采购类别：</div>
          <!-- <input type="text" class="underline-input caigou" placeholder="" /> -->
          <el-select
            v-model="value"
            placeholder="请选择"
            size="small"
            style="width: 690px; border-bottom: 1px solid #000000; padding: 0; background-color: transparent"
            :suffix-transition="false"
            :show-arrow="false"
            :filterable="true"
          >
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="form-row-item">
          <div class="rowtitle">付款方式：</div>
          <!-- <input type="text" class="underline-input caigou" placeholder="" /> -->
          <el-select
            v-model="value1"
            placeholder="请选择"
            size="small"
            style="width: 690px; border-bottom: 1px solid #000000"
            :suffix-transition="false"
            :show-arrow="false"
            :filterable="true"
          >
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="form-row-item">
          <div class="rowtitle">项目名称:</div>
          <input type="text" class="underline-input caigou" placeholder="" />
        </div>
        <div class="form-row-item">
          <div class="rowtitle">合同编号:</div>
          <input type="text" class="underline-input caigou" placeholder="" />
        </div>
        <div class="form-row-item" style="margin-top: 5px">
          <div class="rowtitle">付款明细：:</div>
        </div>
      </div>
      <table>
        <tr>
          <th class="headth">序号</th>
          <th class="headthb">合同编号</th>
          <th class="headtcb">承包商</th>
          <th class="headtkh">开户行</th>
          <th class="headthyh">银行账号</th>
          <th class="headthje">合同金额</th>
          <th class="headthfk">付款金额</th>
        </tr>
        <tr v-for="(item, index) in parameter.filteredItems.slice(0, 5)" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.username }}</td>
          <td>{{ getGenderType().find(itemW => itemW.genderValue === item.gender)?.genderLabel }}</td>
          <td>{{ item.kaihuname }}</td>
          <td>{{ formatNumberWithSpaces(item.backname) }}</td>
          <td>{{ formatToRMB22(item.hetongjine) }}</td>
          <td>{{ formatToRMB22(item.fukuanzonge) }}</td>
        </tr>
      </table>

      <div class="form-row">
        <div class="form-row-item" style="margin-top: 0px">
          <div class="rowtitle">申请描述</div>
        </div>
      </div>

      <textarea v-if="isShow" name="" id="myTextarea" class="textareaClass" v-model="cshh"></textarea>
      <div v-else v-html="cshh && cshh.replace(/(\n|\r|\r\n)/g, '<br />')" class="textareaClass" />
      <!-- <el-input type="textarea" placeholder="只能输入2000个字符" :rows="6" maxlength="2000" /> -->

      <div class="form-row">
        <div class="form-row-item" style="margin-top: 0px">
          <div class="rowtitle">请款状态：:</div>
        </div>
      </div>
      <table class="qingkuan">
        <tr>
          <th class="headth">序号</th>
          <th class="headthb">付款</th>
          <th class="headtcb">金额</th>
          <th class="headtkh">发票</th>
          <th class="headthyh">金额</th>
          <th class="headthje">备注</th>
        </tr>
        <tr>
          <td>1</td>
          <td>已付金额</td>
          <td>
            <input
              type="text"
              class="underline-input"
              v-model="inputValue3"
              @input="formatCurrency7"
              @blur="finalizeFormat7"
              style="
                width: 100px;
                text-align: center;
                border: none;
                font-size: 10px;
                padding: 0;
                box-sizing: border-box;
                line-height: 22px;
              "
            />
          </td>
          <td>已收发票</td>
          <td>
            <input
              type="text"
              class="underline-input"
              v-model="inputValue"
              @input="formatCurrency"
              @blur="finalizeFormat"
              style="
                width: 100px;
                text-align: center;
                border: none;
                font-size: 10px;
                padding: 0;
                box-sizing: border-box;
                line-height: 22px;
              "
            />
          </td>
          <td></td>
        </tr>
        <tr>
          <td>2</td>
          <td>本次请款</td>
          <td>{{ qingkuan[1].value }}</td>
          <td></td>
          <td>
            <input
              type="text"
              class="underline-input"
              style="
                width: 100px;
                text-align: center;
                border: none;
                font-size: 10px;
                padding: 0;
                box-sizing: border-box;
                line-height: 22px;
              "
            />
          </td>
          <td></td>
        </tr>
        <tr>
          <td>3</td>
          <td>剩余</td>
          <td>
            <input
              type="text"
              class="underline-input"
              v-model="inputValue1"
              @input="formatCurrency5"
              @blur="finalizeFormat5"
              style="
                width: 100px;
                text-align: center;
                border: none;
                font-size: 10px;
                padding: 0;
                box-sizing: border-box;
                line-height: 22px;
              "
            />
          </td>
          <td>剩余发票</td>
          <td>
            <input
              type="text"
              class="underline-input"
              v-model="inputValue2"
              @input="formatCurrency1"
              @blur="finalizeFormat1"
              style="
                width: 100px;
                text-align: center;
                border: none;
                font-size: 10px;
                padding: 0;
                box-sizing: border-box;
                line-height: 22px;
              "
            />
          </td>
          <td></td>
        </tr>
        <tr>
          <td>4</td>
          <td>合同金额</td>
          <td>{{ qingkuan[3].value }}</td>
          <td></td>
          <td>
            <input
              type="text"
              class="underline-input"
              style="
                width: 100px;
                text-align: center;
                border: none;
                font-size: 10px;
                padding: 0;
                box-sizing: border-box;
                line-height: 22px;
              "
            />
          </td>
          <td></td>
        </tr>
      </table>
      <div class="form-row">
        <div class="form-row-item" style="margin-top: 0px">
          <div class="rowtitle">本次请款</div>
        </div>
      </div>
      <!-- 底部 -->
      <div class="bomBox">
        <div class="bomBoxItem">
          <div class="bomBoxItem-1">
            <div></div>
            <div>￥{{ sumField(parameter.filteredItems.slice(0, 5), "fukuanzonge") }}</div>
          </div>
          <div class="bomBoxItem-2">
            <div class="caigou-item" v-for="(item, index) in caigouList" :key="index" @click="caigouClick(item, index)">
              <div class="cone">{{ item.name }}</div>
              <div class="ctwo" :class="{ activecaigou: caigouIndex == index }"></div>
            </div>
          </div>
          <div class="bomBoxItem-3" v-for="(item, index) in item3List" :key="index">
            <div class="threecai">{{ item.name }}:</div>
            <input type="text" class="underline-input caigou" placeholder="" style="width: 100%" />
          </div>
        </div>
        <div class="bomBoxItem">
          <div class="bomBoxItem-1">
            <div>发票抬头：</div>
            <div>美登思能源技术（上海）有限公司</div>
          </div>
          <div class="bomBoxItem-2">
            <div class="caigou-item" v-for="(item, index) in fapiaoList" :key="index" @click="fapiaoClick(item, index)">
              <div class="cone">{{ item.name }}</div>
              <div class="ctwo" :class="{ activecaigou: fapiaoIndex == index }"></div>
            </div>
          </div>
          <div class="bomBoxItem-3 riqiitem" v-for="(item, index) in item4List" :key="index">
            <div class="threecai">{{ item.name }}:</div>
          </div>
          <!-- <div class="bomBoxItem-3 riqiitem">
            <div class="threecai fapiaoXUI">发票金额：</div>
            <div class="threecai fapiaoXUI" style="margin-left: 70px">发票号码：</div>
          </div> -->
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="daYin">打印</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 生成的图片预览 -->
  <div v-if="imageUrl" class="preview" id="previewCs">
    <img :src="imageUrl" alt="生成的图片" style="width: 100%; height: 100%" />
  </div>
</template>

<script setup lang="ts" name="Print">
import { nextTick, ref, onUnmounted } from "vue";
import { getGenderType, getKaihuType } from "@/utils/dict.ts";
import printJS from "print-js";
import html2canvas from "html2canvas";
import { getCountryList, setCountryList, selectData } from "@/api/modules/user";
export interface ExcelParameterProps {
  title: string; // 标题
  fileSize?: number; // 上传文件的大小
  fileType?: File.ExcelMimeType[]; // 上传文件的类型
  tempApi?: (params: any) => Promise<any>; // 下载模板的Api
  importApi?: (params: any) => Promise<any>; // 批量导入的Api
  getTableList?: () => void; // 获取表格数据的Api
}

const cshh = ref(""); // 申请描述
const isShow = ref(true); // 申请描述

// dialog状态
const dialogVisible = ref(false);
// 父组件传过来的参数
const parameter = ref<any>({
  title: "",
  fileSize: 5,
  fileType: ["application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]
});

function formatNumberWithSpaces(input) {
  const str = input.toString().replace(/\D/g, "");
  return str.replace(/(\d{4})(?=\d)/g, "$1 ");
}
/**
 * 生成 ME{YY}-{MM}-P{DD} 格式的编号
 * @param {Date} [date] - 可选，指定日期，默认使用当前日期
 * @returns {string} - 返回格式如 ME25-07-P005
 */
function generateMECode(date = new Date()) {
  // 获取年份后两位（如 2025 → 25）
  const year = date.getFullYear().toString().slice(-2);

  // 获取月份，补零到2位（如 7 → 07）
  const month = (date.getMonth() + 1).toString().padStart(2, "0");

  // 获取日期，补零到3位（如 5 → 005）
  const day = date.getDate().toString().padStart(3, "0");

  // 拼接成 ME25-07-P005 格式
  return `MEN${year}-${month}-P`;
  // return `MEN${year}-${month}-P${day}`;
}

function getCurrentDateFormatted(date = new Date()) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}/${month}/${day}`;
}

const inputValue = ref("");
const inputValue1 = ref("");
const inputValue2 = ref("");
const inputValue3 = ref("");

// 实时格式化
const formatCurrency = event => {
  let value = event.target.value.replace(/[^\d.]/g, "");

  // 防止多个小数点
  const decimalCount = (value.match(/\./g) || []).length;
  if (decimalCount > 1) {
    value = value.substring(0, value.lastIndexOf("."));
  }

  // 分割整数和小数部分
  let [integer, decimal] = value.split(".");

  // 添加千位分隔符
  if (integer) {
    integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  // 组合新值
  let newValue = integer || "";
  if (decimal !== undefined) {
    newValue += `.${decimal.substring(0, 2)}`;
  }

  // 更新输入框值（不触发无限循环）
  if (event.target.value !== `${newValue}`) {
    inputValue.value = `${newValue}`;
  }
};
// 失去焦点时完成格式化
const finalizeFormat = () => {
  let value = inputValue.value.replace(/[^\d.]/g, "");
  const numValue = parseFloat(value || 0);

  // 格式化为两位小数
  inputValue.value = `${numValue.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
};
// 实时格式化
const formatCurrency1 = event => {
  let value = event.target.value.replace(/[^\d.]/g, "");

  // 防止多个小数点
  const decimalCount = (value.match(/\./g) || []).length;
  if (decimalCount > 1) {
    value = value.substring(0, value.lastIndexOf("."));
  }

  // 分割整数和小数部分
  let [integer, decimal] = value.split(".");

  // 添加千位分隔符
  if (integer) {
    integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  // 组合新值
  let newValue = integer || "";
  if (decimal !== undefined) {
    newValue += `.${decimal.substring(0, 2)}`;
  }

  // 更新输入框值（不触发无限循环）
  if (event.target.value !== `${newValue}`) {
    inputValue2.value = `${newValue}`;
  }
};
// 失去焦点时完成格式化
const finalizeFormat1 = () => {
  let value = inputValue2.value.replace(/[^\d.]/g, "");
  const numValue = parseFloat(value || 0);

  // 格式化为两位小数
  inputValue2.value = `${numValue.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
};
// 实时格式化
const formatCurrency5 = event => {
  let value = event.target.value.replace(/[^\d.]/g, "");

  // 防止多个小数点
  const decimalCount = (value.match(/\./g) || []).length;
  if (decimalCount > 1) {
    value = value.substring(0, value.lastIndexOf("."));
  }

  // 分割整数和小数部分
  let [integer, decimal] = value.split(".");

  // 添加千位分隔符
  if (integer) {
    integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  // 组合新值
  let newValue = integer || "";
  if (decimal !== undefined) {
    newValue += `.${decimal.substring(0, 2)}`;
  }

  // 更新输入框值（不触发无限循环）
  if (event.target.value !== `${newValue}`) {
    inputValue1.value = `${newValue}`;
  }
};
// 失去焦点时完成格式化
const finalizeFormat5 = () => {
  let value = inputValue1.value.replace(/[^\d.]/g, "");
  const numValue = parseFloat(value || 0);

  // 格式化为两位小数
  inputValue1.value = `${numValue.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
};
// 实时格式化
const formatCurrency7 = event => {
  let value = event.target.value.replace(/[^\d.]/g, "");

  // 防止多个小数点
  const decimalCount = (value.match(/\./g) || []).length;
  if (decimalCount > 1) {
    value = value.substring(0, value.lastIndexOf("."));
  }

  // 分割整数和小数部分
  let [integer, decimal] = value.split(".");

  // 添加千位分隔符
  if (integer) {
    integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  // 组合新值
  let newValue = integer || "";
  if (decimal !== undefined) {
    newValue += `.${decimal.substring(0, 2)}`;
  }

  // 更新输入框值（不触发无限循环）
  if (event.target.value !== `${newValue}`) {
    inputValue3.value = `${newValue}`;
  }
};
// 失去焦点时完成格式化
const finalizeFormat7 = () => {
  let value = inputValue3.value.replace(/[^\d.]/g, "");
  const numValue = parseFloat(value || 0);

  // 格式化为两位小数
  inputValue3.value = `${numValue.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
};
const numbercon = ref("");
// 接收父组件参数
const acceptParams = async (params: ExcelParameterProps, type: string) => {
  startTimer();
  isShow.value = true;
  parameter.value = { ...parameter.value, ...params };
  console.log("params", parameter.value);
  dialogVisible.value = true;
  const res = await getCountryList({ type: type });
  if (res.success) {
    numbercon.value = res.data[0].contnumber;
  }
  qingkuan.value = [
    {
      name: "已付金额",
      value: 0.0
    },
    {
      name: "本次请款",
      value: sumField(parameter.value.filteredItems.slice(0, 5), "fukuanzonge")
    },
    {
      name: "剩余",
      value: 0.0
    },
    {
      name: "合同金额",
      value: sumField(parameter.value.filteredItems.slice(0, 5), "hetongjine")
    },
    {
      name: "已收发票",
      value: 0.0
    },
    {
      name: "剩余发票",
      value: 0.0
    }
  ];
};

const PrintRefs = ref<HTMLElement | null>(null);
const imageUrl = ref<string>("");

const captureElement = async () => {
  isShow.value = false;

  nextTick(async () => {
    // setTimeout(async () => {
    if (!PrintRefs.value) return;

    try {
      const canvas = await html2canvas(PrintRefs.value, {
        scale: 4, // 基础缩放
        dpi: 300, // 显式设置DPI
        letterRendering: true, // 提高文本渲染质量
        allowTaint: true, // 允许污染画布（必要时）
        useCORS: true, // 跨域资源
        logging: true // 开发时可开启查看过程
      });

      imageUrl.value = canvas.toDataURL("image/png");
    } catch (error) {
      console.error("Error capturing element:", error);
      isShow.value = true;
    }
    // }, 100);
  });
};
let timer: any = null;
// 实时获取编号
// const dataFun = async () => {
//   const res = await selectData({ type: "eng" });
//   if (res.success) {
//     numbercon.value = res.value;
//   }
// };
const dataFun = async () => {
  const res = await selectData({ type: "me" });
  if (res.success) {
    // 将数字转换为字符串并在前面补零，确保总长度为3位
    numbercon.value = String(res.value).padStart(3, "0");
  }
};
const daYin = async () => {
  captureElement();
  // return;
  await nextTick();
  await setCountryList({ type: "eng" });
  setTimeout(() => {
    printJS({
      printable: "previewCs", // 要打印的DOM元素ID
      type: "html"
      // header: "我的打印文档",
      // headerStyle: "color: red;"
      // css: "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" // 可选，引入外部CSS
    });
    // isShow.value = true;
  }, 350);
};

const value = ref("");
const value1 = ref("");

const options = [
  {
    value: "Option1",
    label: "A-生产类"
  },
  {
    value: "Option2",
    label: "B-研发类"
  },
  {
    value: "Option3",
    label: "C-办公耗材&固定资产类"
  }
];
const options1 = [
  {
    value: "Option1",
    label: "A-预付款，发货前付全款"
  },
  {
    value: "Option2",
    label: "B-全款付讫后发货"
  },
  {
    value: "Option3",
    label: "C-货已到，票已到，请款（月结）"
  }
];

const handleDialogClose = () => {
  stopTimer();
};

const item3List = ref([
  {
    name: "采购员"
  },
  {
    name: "采购负责人"
  },
  {
    name: "财务复核"
  },
  {
    name: "总经理"
  }
  // {
  //   name: "发票情况"
  // }
]);
const item4List = ref([
  {
    name: "日期："
  },
  {
    name: "日期："
  },
  {
    name: "日期："
  },
  {
    name: "日期："
  }
]);

const caigouList = ref([
  {
    name: "采购"
  },
  {
    name: "分包"
  }
]);
const fapiaoList = ref([
  {
    name: "其他"
  }
]);
const caigouIndex = ref(0);
const caigouClick = (item, index) => {
  caigouIndex.value = index;
};
const fapiaoIndex = ref(null);
const fapiaoClick = (item, index) => {
  fapiaoIndex.value = index;
};

/**
 * 将数字格式化为人民币金额格式（带千位分隔符）
 * @param {number|string} num - 要格式化的数字或数字字符串
 * @returns {string} - 返回格式如 ￥14,122,081.05
 */
function formatToRMB(num) {
  // 1. 转换为数字并检查合法性
  const number = Number(num);
  if (isNaN(number)) {
    throw new Error("Invalid number input");
  }

  // 2. 固定保留2位小数，并添加千位分隔符
  const parts = number.toFixed(2).split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");

  // 3. 拼接成人民币格式
  return `${parts.join(".")}`;
}
function formatToRMB22(num) {
  // 1. 转换为数字并检查合法性
  const number = Number(num);
  if (isNaN(number)) {
    throw new Error("Invalid number input");
  }

  // 2. 固定保留2位小数，并添加千位分隔符
  const parts = number.toFixed(2).split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");

  // 3. 拼接成人民币格式
  return `${parts.join(".")}`;
}

/**
 * 计算对象数组中指定字段的总和（保留两位小数）
 * @param {Array} items - 对象数组
 * @param {string} field - 要求和的字段名
 * @returns {number} 保留两位小数的总和
 */
function sumField(items, field) {
  if (!Array.isArray(items) || typeof field !== "string") {
    return 0.0;
  }

  const sum = items.reduce((total, item) => {
    if (item && item[field] !== undefined && item[field] !== null) {
      // 处理各种可能的输入格式
      const value = parseFloat(
        String(item[field])
          .replace(/[^\d.-]/g, "") // 移除非数字字符（保留小数点和负号）
          .trim()
      );
      return total + (isNaN(value) ? 0 : value);
    }
    return formatToRMB(total);
  }, 0);

  // 保留两位小数并转换为数字类型（避免返回字符串）
  return formatToRMB(parseFloat(sum.toFixed(2)));
}

const qingkuan = ref([
  {
    name: "已付金额",
    value: 0.0
  },
  {
    name: "本次请款",
    value: 0.0
  },
  {
    name: "剩余",
    value: 0.0
  },
  {
    name: "合同金额",
    value: 0.0
  },
  {
    name: "已收发票",
    value: 0.0
  },
  {
    name: "剩余发票",
    value: 0.0
  }
]);

// 启动定时器
const startTimer = () => {
  // 立即执行一次
  dataFun();
  // 然后每5秒执行一次
  timer = setInterval(dataFun, 5000);
};

// 停止定时器
const stopTimer = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

// 组件销毁时自动停止定时器
onUnmounted(() => {
  stopTimer();
});

defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
.textareaClass {
  white-space: pre-wrap; /* 保留换行和空格 */
  // font-family: monospace; /* 可选：等宽字体更易对齐 */
  font-size: 10px; /* 可选：调整字体大小 */
  color: #000; /* 可选：调整文本颜色 */
  // font-weight: bold;
}
// @use "index";
</style>
